<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>

      <row-list :col="2">
        <row-item>
          <a-form-item
            label="工单类别"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select @change="changePlanFlag" v-decorator="['category', {rules: [{required: true, message: '计划性维修不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in planFlagMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="完成时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              showTime
              v-decorator="['repairEndTime']"
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
            />
          </a-form-item>
        </row-item>
        <!--        <row-item>
          <a-form-item
            label="紧急等级"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['level', {initialValue: 1, rules: [{required: true, message: '紧急等级不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in levelMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="故障类别"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-tree-select
              style="width: 100%"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="treeData"
              :treeNodeFilterProp="'title'"
              :showSearch="true"
              v-decorator="['repairErrorTypeId']"
              placeholder="请选择"
            >
            </a-tree-select>
          </a-form-item>
        </row-item>-->

        <!--<row-item>
          <a-form-item
            label="维修耗时"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              style="width: 100%"
              :min="1"
              :step="0.01"
              type="number"
              addonAfter="分钟"
              v-decorator="['repairMinutes', {initialValue:1, rules: [{required: false, message: '维修耗时不能为空'}]}]" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="更换备件"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-button type="primary" @click="handleAddPartUsed">更换备件</a-button>
          </a-form-item>
        </row-item>-->
      </row-list>
      <row-list :col="1">
        <row-item>
          <a-form-item
            label="维修描述"
            :labelCol="BaseTool.Constant.labelCol2"
            :wrapperCol="BaseTool.Constant.wrapperCol2"
          >
            <a-textarea v-decorator="['repairContent']"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="维修图片"
            :labelCol="BaseTool.Constant.labelCol2"
            :wrapperCol="BaseTool.Constant.wrapperCol2"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="true"
              list-type="picture"
              :file-list="defaultRepairFileList"
              @change="handleRepairFileChange"
              accept="image/*"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 上传图片 </a-button>
            </a-upload>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <spare-part-used-select-modal ref="sparePartUsedSelectModal" />
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { finish } from '@/api/repair/application-form'
import { queryUser } from '@/api/upms/user'
import { fetchErrorTypeTree } from '@/api/repair/errortype'
import SparePartUsedSelectModal from '@/views/sqarepartmanage/sparepartused/modules/SparePartUsedSelectModal'
import { uploadUrl } from '@/api/upms/file'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'BaseRepairApplicationForm',
  data () {
    return {
      model: null,
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      category: 0,
      planFlagMap: {},
      // 下拉框map
      treeData: [],
      descripitionMap: {},
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      sourceMap: {},
      levelMap: {},
      needStopMap: {},
      statusMap: {},
      uploadUrl: uploadUrl,
      defaultRepairFileList: [],
      repairFileList: [], // 维修图片,
      userList: []
    }
  },
  components: {
    SparePartUsedSelectModal
  },
  props: {
  },
  created () {
    // 下拉框map
    this.sourceMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_SOURCE)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_LEVEL)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_STATUS)
    this.needStopMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
    this.descripitionMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIRE_ACTION)
    this.planFlagMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_CATEGORY)
  },
  methods: {
    base (record) {
      this.setTree()
      this.visible = true
      this.model = record
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        return
      }
      this.modalTitle = '维修完成'
      this.repairFileList = record.repairFileList
      this.defaultRepairFileList = this.BaseTool.UPLOAD.transImg(this.repairFileList)
      const { form: { setFieldsValue } } = this
      // 日期处理
      record.repairEndTime = this.BaseTool.Date.formatter(record.repairEndTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'needStop',
          'level',
          'category',
          'repairErrorTypeId',
          'repairEndTime'
        ])))
      })
    },
    getUsers () {
      queryUser({ status: 1 }).then(res => {
        this.userList = res.data
      })
    },
    changePlanFlag (value) {
      this.category = value
      const { form: { setFieldsValue } } = this
      if (this.category === 1) {
        this.$nextTick(() => {
          setFieldsValue({ needStop: 1 })
        })
      } else {
        this.$nextTick(() => {
          setFieldsValue({ needStop: 0 })
        })
      }
    },
    handleRepairFileChange (info) {
      this.defaultRepairFileList = info.fileList
      this.repairFileList = this.setFileList(info, 12)
    },
    setFileList (info, type) {
      const file = info.file
      const fileList = info.fileList
      if (file.status === 'done') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'removed') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'error') {
        this.$message.error('上传失败')
        return []
      }
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期处理
        values.repairFileList = this.repairFileList
        values.repairEndTime = this.BaseTool.Date.formatter(values.repairEndTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        finish(values).then(() => {
          this.$message.info('维修完成，请完成后续维修报告，完成后提交审核；')
          this.handleCancel(values)
        }).catch(() => {
          this.confirmLoading = false
        })
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok')
      }
    },
    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base({}, { filter: 0, status: 2 })
    },
    handleSbSelectd (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbId': key,
          'sbName': row.name
        }))
      })
    },
    handlePartSelect () {
      const sbId = this.form.getFieldValue('sbId')
      this.$refs.partInfoSelectModal.base({ sbId })
    },
    handlePartSelected (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'partId': key,
          'partName': row.name
        }))
      })
    },
    /**
     * 设置类别树
     */
    setTree (record = {}) {
      fetchErrorTypeTree({ id: record.id }).then(res => {
        this.treeData = res.data
      })
    },
    handleAddPartUsed () {
      /* const modal = this.$refs.repairFeeModal
      modal.base(null, record) */
      this.$refs.sparePartUsedSelectModal.base(this.model, { sbId: this.model.sbId, modelId: this.model.modelId })
    }

  }
}
</script>
